package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.web.admin.context.LoginUserContext;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.service.UserInfoService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * ClassName:AuthenticationInterceptor
 * Package: com.atguigu.lease.web.admin.custom.interceptor
 * Description:
 *
 * @Author Makabaka
 * @Create 2024/9/25 19:56
 * @Version 1.0
 */
//自定义的拦截器
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    private SystemUserService systemUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("access_token");

        if (token == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }else {
//            对token进行解析  正确才进行下一步  不正确返回错误信息
//            将token中的userId获取到 并查询到用户的信息  存在ThreadLocal中
//            ThreadLocal可以在同一个线程内共享数据
            long userId = JwtUtil.parseToken(token);
            System.out.println(userId);  //登录user  id=2
            SystemUser systemUser = systemUserService.getById(userId);
//            存到ThreadLocal中  为后续登录显示数据共享数据
            LoginUserContext.setLoginUser(systemUser);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        在操作结束后将ThreadLocal清除掉  否则可能会导致oom  内存溢出异常
        LoginUserContext.clear();
    }
}
